package com.automapper.sqlbuilder.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.automapper.constants.ParameterConstants;
import com.automapper.exception.AutoMapperException;
import com.automapper.sqlbuilder.SqlBuilderTemplate;
import com.automapper.utils.ParameterUtils;
import com.automapper.utils.PropertiesFacade;

public class InsertMapSqlBuilder extends SqlBuilderTemplate {	
	
	private static final String VALUE = " #{%s[%s].%s} ";
	
	@Override
	public String buildSql(Object parameterObject, PropertiesFacade propertiesFacade) throws Exception {   
		AutoMapperException.NullRuntimeException(parameterObject, "Sorry,I refuse to build sql for a null object!");
		
		List<String> values = new ArrayList<>();
		Map<String, Object> parameterMap = (Map<String, Object>) parameterObject;
		//获取传入参数
		List<Object> list = ParameterUtils.getParameterList(parameterMap);
		
		String tableName = getTableName(parameterMap);
		Map<Object,Object> data = (Map<Object, Object>) list.get(0);
		//Arrays.asList生成List对象不能使用removeall方法，所以再通过new ArrayList才可以进行对其进行removall操作
		List<String> keys = Arrays.asList(data.keySet().toArray(new String[]{}));
		List<String> columns = new ArrayList(keys);
		this.filter(parameterMap, columns);
		
		StringBuilder tableSql = new StringBuilder();  
		StringBuilder valueSql = new StringBuilder(); 
	    tableSql.append("insert into ").append(tableName).append("(").append(StringUtils.join(columns, ",")).append(")");  
	    valueSql.append(" values ");
	    
	    for (int i = 0; i  < list.size(); i++) {
	    	Map<Object, Object> map = (Map<Object, Object>) list.get(i);
	    	
	    	valueSql.append("(");
	    	if (propertiesFacade.isNullToDefaultValue()) {
	    		//但值为null，赋值空字符串
	    		values.addAll(this.getInserValueNullToEmptyStr(map, columns, i));
	    	} else {
	    		values.addAll(this.getInserValue(columns, i));
	    	}
		    valueSql.append(StringUtils.join(values, ","));  
		    valueSql.append("),");
		    values.clear();
	    }
	    valueSql.delete(valueSql.lastIndexOf(","), valueSql.lastIndexOf(",") + 1);  
	    return tableSql.append(valueSql).toString();
	} 
	
	/**
	 * 生成入库参数
	 * @param obj 入库对象
	 * @param columns 数据库字段名
	 * @param index
	 * @return
	 * @throws Exception 
	 */
	private List<String> getInserValue(List<String> columns, int index) throws Exception {
		List<String> list = new ArrayList<>();
		for (String column : columns) {
			//生成sql参数，参数采用ognl表达式：list[0].xxx
    		list.add(String.format(VALUE, ParameterConstants.PARAM, index, column));
		}
	    return list;
	}
	
	/**
	 * 生成入库参数，对象String类型是null转换空字符串
	 * @param obj 入库对象
	 * @param columns 数据库字段名
	 * @param index
	 * @return
	 * @throws Exception 
	 */
	private List<String> getInserValueNullToEmptyStr(Map<Object,Object> map, List<String> columns, int index) throws Exception {
		List<String> list = new ArrayList<>();
		for (String column : columns) {
			Object obj = map.get(column);
			if (obj == null) {
				list.add("''");
			} else {
				//生成sql参数，参数采用ognl表达式：list[0].xxx
				list.add(String.format(VALUE, ParameterConstants.PARAM, index, column));
			}
		}
		return list;
	}
}
